Page({
  data: {
    name: '',
    gender: 1,
    mobile: '',
    currentDate: Date.now(),
    maxDate:Date.now() + 1000 * 60 * 60 * 24 * 3,
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [],
  },
  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },
  selectHouse(ev){
    console.log(ev.detail)
    this.setData({
      houseId:ev.detail.id,
      houseName:ev.detail.name
    })
  },
  selectDate(ev){
    console.log(ev.detail)
    this.setData({
      dateLayerVisible:false,
      visitDate:wx.utils.formatDate(ev.detail)
    })
  },
  onLoad(){
    this.getHouseList()
  },
  async getHouseList(){
    const {code,data} = await wx.http.get('/house')
    if(code !== 10000) return wx.utils.toast()
    this.setData({
      houseList:data
    })
  },
  verifyHouse() {
    const valid = !!this.data.houseName
    // 验证结果提示
    if (!valid) wx.utils.toast('请选择房屋信息!')
    // 返回验证结果
    return valid
  },
  // 验证业主姓名（必须为汉字）
  verifyName() {
    // 正则表达式
    const reg = /^[\u4e00-\u9fa5]{2,5}$/
    // 验证业主姓名
    const valid = reg.test(this.data.name.trim())
    // 验证结果提示
    if (!valid) wx.utils.toast('请填写真实中文姓名!')
    // 返回验证结果
    return valid
  },
  verifyMobile() {
    // 验证手机号
    const reg = /^[1][3-8]\d{9}$/
    const valid = reg.test(this.data.mobile)
    // 验证结果提示
    if (!valid) wx.utils.toast('请填写正确的手机号码!')
    // 返回验证结果
    return valid
  },
  async submitForm() {
    if (!this.verifyHouse()) return
    if (!this.verifyName()) return
    if (!this.verifyMobile()) return
    const {houseId,name,gender,mobile,visitDate} = this.data
    const {code} = await wx.http.post('/visitor',{
      houseId,name,gender,mobile,visitDate
    })
    if(code !== 10000) return wx.utils.toast()
    // 跳转到访客列表页
    wx.navigateTo({
      url: '/visitor_pkg/pages/list/index'
    })
  },
}) 
